import { BrowserWindow, shell, Menu, globalShortcut } from 'electron'
import { join } from 'path'
import { is } from '@electron-toolkit/utils'
import Logger from './logger.js'
import appConfig from '../config/app-config.js'

// 导出创建主窗口的函数
export function createMainWindow(__dirname_local, ffmpegManager, hlsHttpServer) {
  try {
    // 创建浏览器窗口
    const mainWindow = new BrowserWindow(appConfig.browserWindowConfig)

    // 窗口准备好显示时触发
    mainWindow.on('ready-to-show', () => {
      console.log('Window is ready to show')
      mainWindow.show()
    })

    // 监听页面加载失败事件
    mainWindow.webContents.on(
      'did-fail-load',
      (event, errorCode, errorDescription, validatedURL) => {
        console.error(`Failed to load ${validatedURL}: ${errorDescription} (${errorCode})`)
      }
    )

    // 监听页面加载完成事件
    mainWindow.webContents.on('did-finish-load', () => {
      console.log('Page loaded successfully')
    })

    mainWindow.webContents.setWindowOpenHandler((details) => {
      shell.openExternal(details.url)
      return { action: 'deny' }
    })

    // 打印当前环境变量以调试
    console.log('is:', is)
    console.log('is.dev:', is.dev)
    console.log('ELECTRON_RENDERER_URL:', process.env['ELECTRON_RENDERER_URL'])
    console.log('NODE_ENV:', process.env.NODE_ENV)
    Logger.info('当前环境变量:', process.env)

    // 加载HTML文件
    if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
      console.log('Loading development URL:', process.env['ELECTRON_RENDERER_URL']) // http://localhost:5173
      mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL'])
    } else {
      // 修复生产环境的路径 - 使用绝对路径确保正确加载
      const indexPath = join(__dirname_local, '../dist/renderer/index.html')
      mainWindow.loadFile(indexPath)
    }

    return mainWindow
  } catch (error) {
    console.error('Error creating window:', error)
    throw error
  }
}

// 创建应用菜单
export function createApplicationMenu() {
  const menuTemplate = [
    {
      label: '视图',
      submenu: [
        {
          label: '刷新',
          accelerator: 'CommandOrControl+R',
          click: (_, focusedWindow) => {
            if (focusedWindow) {
              // 使用与全局快捷键相同的刷新逻辑
              if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
                focusedWindow.loadURL(process.env['ELECTRON_RENDERER_URL'])
              } else {
                // 生产环境下重新加载HTML文件，使用绝对路径确保正确加载
                const __filename = fileURLToPath(import.meta.url)
                const __dirname_local = dirname(__filename)
                const indexPath = join(__dirname_local, '../../../dist/renderer/index.html')
                focusedWindow.loadFile(indexPath)
              }
            }
          }
        },
        {
          label: '开发者工具',
          accelerator: process.platform === 'darwin' ? 'Command+Alt+I' : 'Ctrl+Shift+I',
          click: (_, focusedWindow) => {
            if (focusedWindow) {
              focusedWindow.webContents.toggleDevTools()
            }
          }
        },
        {
          label: '切换全屏',
          accelerator: process.platform === 'darwin' ? 'Command+Ctrl+F' : 'F11',
          click: (_, focusedWindow) => {
            if (focusedWindow) {
              focusedWindow.setFullScreen(!focusedWindow.isFullScreen())
            }
          }
        }
      ]
    },
    {
      label: '帮助',
      submenu: [
        {
          label: '关于',
          click: () => {
            // 实现关于对话框
            console.log('显示关于对话框')
          }
        }
      ]
    }
  ]

  const menu = Menu.buildFromTemplate(menuTemplate)
  Menu.setApplicationMenu(menu)
}

// 向所有窗口发送消息
export function windowsWebContentsSend(channel, ...args) {
  const allWindows = BrowserWindow.getAllWindows()

  allWindows.forEach((window) => {
    window.webContents.send(channel, ...args)
  })
}

// 注册全局快捷键
export function registerGlobalShortcuts() {
  // 注册全局快捷键来打开开发者工具
  globalShortcut.register('F12', () => {
    const focusedWindow = BrowserWindow.getFocusedWindow()
    if (focusedWindow) {
      focusedWindow.webContents.toggleDevTools()
    }
  })
}

// 清理窗口资源
export function cleanupWindowResources() {
  globalShortcut.unregister('CommandOrControl+R')
  globalShortcut.unregister('F12')
}

// 从 url 模块导入 fileURLToPath 和 dirname（需要添加到文件顶部导入中）
import { fileURLToPath } from 'url'
import { dirname } from 'path'